Popular Searches
Popular Course Categories
Popular Courses

Java Basics for Selenium

Java Basics for Selenium

Selenium with Java

Java Basics for Selenium

Java Basics for Selenium covers the fundamental Java programming concepts required to create, understand, execute, debug, and maintain Selenium WebDriver automation scripts. Selenium WebDriver provides the browser automation API, while Java is used to write the programming logic that controls browser actions, handles test data, validates results, manages reusable components, and builds scalable automation frameworks.

Selenium WebDriver provides a programming interface for controlling browsers, and Selenium supports Java as one of its primary language bindings. A typical Java Selenium script creates a WebDriver session, navigates to a page, locates web elements, performs actions, reads information, and finally closes the browser session. :contentReference[oaicite:0]{index=0}

Learning Java before advanced Selenium is important because modern automation frameworks use Java concepts such as classes, objects, inheritance, interfaces, collections, exception handling, methods, packages, file handling, and Object-Oriented Programming.

Explore JustAcademy Selenium Training | Register for Course Demo


1. What is Java?

Java is a high-level, object-oriented programming language used to build applications, enterprise software, web applications, automation tools, and testing frameworks. In Selenium automation, Java acts as the programming language used to implement browser automation logic.

For example, a tester can use Java to create a browser object, define test data, locate web elements, create reusable methods, perform validations, handle exceptions, and organize an entire automation framework.

public class HelloJava {

    public static void main(String[] args) {

        System.out.println("Hello Selenium");

    }

}


2. Why Java is Important for Selenium

  • Java supports Object-Oriented Programming.
  • Java provides strong exception-handling capabilities.
  • Java provides powerful collection classes.
  • Java works with Selenium WebDriver.
  • Java integrates with TestNG and JUnit.
  • Java works with Maven and Gradle.
  • Java supports reusable classes and methods.
  • Java is suitable for Page Object Model frameworks.
  • Java supports data-driven and keyword-driven frameworks.
  • Java is suitable for large and maintainable automation projects.


3. Java and Selenium Relationship

Java

  ↓

Programming Logic

  ↓

Selenium Java Binding

  ↓

WebDriver API

  ↓

Browser Driver

  ↓

Chrome / Firefox / Edge / Safari

  ↓

Web Application

  ↓

Automation Result

Selenium WebDriver is designed as a browser automation interface, while browser-specific driver implementations communicate with the corresponding browser. :contentReference[oaicite:1]{index=1}


4. JDK, JRE and JVM

Before writing Java Selenium programs, it is useful to understand the three important Java components: JDK, JRE, and JVM.

ComponentFull FormPurpose
JDKJava Development KitProvides tools required to develop and compile Java programs
JREJava Runtime EnvironmentProvides the environment required to run Java applications
JVMJava Virtual MachineExecutes Java bytecode


5. JDK for Selenium Automation

The Java Development Kit is required when developing Java-based Selenium projects because the project needs Java development and compilation capabilities.

After installing Java, verify it using:

java -version

Verify the Java compiler:

javac -version


6. First Java Program

public class FirstProgram {

    public static void main(String[] args) {

        System.out.println("Welcome to Selenium Automation");

    }

}

Explanation

  • public defines the access level.
  • class defines a Java class.
  • FirstProgram is the class name.
  • main() is the entry point of a standard Java application.
  • System.out.println() prints information to the console.


7. Java Class

A class is a blueprint used to define properties and behavior. Selenium automation frameworks use classes for test cases, page objects, utilities, browser configuration, test data, and framework components.

public class LoginTest {

 

    public void login() {

        System.out.println("Login operation");

    }

}


8. Java Object

An object is an instance of a class.

LoginTest test = new LoginTest();

 

test.login();

Selenium also uses objects extensively:

WebDriver driver = new ChromeDriver();

Here, driver is a reference to a WebDriver object implemented by ChromeDriver.


9. Java Main Method

public static void main(String[] args) {

    System.out.println("Running Selenium Program");

}

The main method provides the starting point for a simple standalone Java application.


10. Java Comments

// Single-line comment

 

/*

   Multi-line comment

*/

Selenium Example

// Open the login page

driver.get("https://example.com/login");

 

// Enter username

driver.findElement(By.id("username")).sendKeys("admin");


11. Java Variables

A variable stores a value that can be used later in a program.

String username = "admin";

String password = "admin123";

int timeout = 10;

boolean loginSuccessful = true;

Variables are frequently used in Selenium to store URLs, credentials, browser configuration, expected values, test data, WebDriver objects, WebElements, and locator values.


12. Rules for Variable Names

  • A variable can contain letters, digits, underscores, and dollar signs.
  • A variable cannot start with a digit.
  • Java variable names are case-sensitive.
  • Java keywords cannot be used as variable names.
  • Meaningful names should be used.

String loginUrl = "https://example.com/login";

String expectedTitle = "Dashboard";

int maxWaitTime = 10;


13. Java Data Types

Java data types are broadly divided into primitive and reference types.

Data TypeExampleAutomation Usage
byte10Small numeric values
short100Small numeric values
int10Counts, indexes, quantities
long100000LLarge numeric values
float10.5fDecimal values
double99.99Prices and calculations
char'A'Single characters
booleantrueConditions and validation
String"Selenium"Text, URLs and test data


14. String in Java

String is used to represent text. Selenium automation uses Strings extensively for URLs, usernames, passwords, expected messages, page titles, product names, and test data.

String browser = "Chrome";

String username = "admin";

String url = "https://example.com";


15. Important String Methods

String text = "  Selenium Automation  ";

 

System.out.println(text.length());

System.out.println(text.trim());

System.out.println(text.toUpperCase());

System.out.println(text.toLowerCase());

System.out.println(text.contains("Automation"));

MethodPurpose
length()Returns the number of characters
trim()Removes leading and trailing whitespace
toUpperCase()Converts text to uppercase
toLowerCase()Converts text to lowercase
contains()Checks whether text contains a value
equals()Compares String content
equalsIgnoreCase()Compares text without case sensitivity
replace()Replaces characters or text
substring()Extracts part of a String


16. String Comparison

For comparing String content, use equals() rather than using == for content comparison.

String expected = "Dashboard";

String actual = "Dashboard";

 

if (expected.equals(actual)) {

    System.out.println("Title matched");

}

Selenium Example

String actualTitle = driver.getTitle();

 

if (actualTitle.equals("Dashboard")) {

    System.out.println("Test Passed");

}


17. Integer

The int type is useful for quantities, indexes, counts, timeouts, and numeric test data.

int timeout = 10;

int quantity = 3;

int expectedCount = 5;


18. Boolean

A boolean contains either true or false.

boolean isLoggedIn = true;

boolean isAdmin = false;

Selenium Example

WebElement button = driver.findElement(By.id("login"));

 

boolean enabled = button.isEnabled();

 

if (enabled) {

    button.click();

}


19. Java Operators

CategoryOperatorsExample
Arithmetic+, -, *, /, %a + b
Relational==, !=, >, <, >=, <=a > b
Logical&&, ||, !a && b
Assignment=, +=, -=, *=, /=a += 5
Increment++a++
Decrement--a--


20. Arithmetic Operators

int price = 500;

int quantity = 2;

 

int total = price * quantity;

 

System.out.println(total);

Selenium Example

int productPrice = 500;

int quantity = 3;

 

int expectedTotal = productPrice * quantity;

 

System.out.println("Expected Total: " + expectedTotal);


21. Relational Operators

int expected = 100;

int actual = 100;

 

if (actual == expected) {

    System.out.println("Value matched");

}


22. Logical Operators

String username = "admin";

String password = "admin123";

 

if (username.equals("admin") &&

    password.equals("admin123")) {

 

    System.out.println("Valid credentials");

}


23. if Statement

if (username.equals("admin")) {

    System.out.println("Valid username");

}


24. if-else Statement

if (loginSuccessful) {

    System.out.println("Login Passed");

} else {

    System.out.println("Login Failed");

}


25. else-if Statement

String status = "Success";

 

if (status.equals("Success")) {

    System.out.println("Test Passed");

} else if (status.equals("Failed")) {

    System.out.println("Test Failed");

} else {

    System.out.println("Unknown Status");

}


26. switch Statement

String browser = "Chrome";

 

switch (browser) {

    case "Chrome":

        System.out.println("Chrome selected");

        break;

 

    case "Firefox":

        System.out.println("Firefox selected");

        break;

 

    case "Edge":

        System.out.println("Edge selected");

        break;

 

    default:

        System.out.println("Unsupported browser");

}


27. for Loop

A for loop repeats a block of code while a condition remains true.

for (int i = 1; i <= 5; i++) {

    System.out.println(i);

}

Selenium Example

List<WebElement> links =

        driver.findElements(By.tagName("a"));

 

for (WebElement link : links) {

    System.out.println(link.getText());

}


28. while Loop

int count = 1;

 

while (count <= 3) {

    System.out.println(count);

    count++;

}


29. do-while Loop

int count = 1;

 

do {

    System.out.println(count);

    count++;

} while (count <= 3);


30. break Statement

for (int i = 1; i <= 10; i++) {

 

    if (i == 5) {

        break;

    }

 

    System.out.println(i);

}


31. continue Statement

for (int i = 1; i <= 5; i++) {

 

    if (i == 3) {

        continue;

    }

 

    System.out.println(i);

}


32. Arrays

An array stores multiple values of the same type.

String[] browsers = {

    "Chrome",

    "Firefox",

    "Edge"

};

 

System.out.println(browsers[0]);

Selenium Example

String[] urls = {

    "https://example.com",

    "https://example.org",

    "https://example.net"

};

 

for (String url : urls) {

    driver.get(url);

    System.out.println(driver.getTitle());

}


33. Array Length

String[] browsers = {

    "Chrome",

    "Firefox",

    "Edge"

};

 

System.out.println(browsers.length);


34. Enhanced for Loop

String[] browsers = {

    "Chrome",

    "Firefox",

    "Edge"

};

 

for (String browser : browsers) {

    System.out.println(browser);

}


35. Methods in Java

A method is a reusable block of code that performs a particular task. Methods are extremely important in Selenium because they allow repetitive browser operations to be reused.

public static void printMessage() {

    System.out.println("Selenium Automation");

}


36. Calling a Method

public class Test {

 

    public static void printMessage() {

        System.out.println("Running Test");

    }

 

    public static void main(String[] args) {

        printMessage();

    }

}


37. Method Parameters

Parameters allow data to be passed into a method.

public static void login(

        String username,

        String password) {

 

    System.out.println(username);

    System.out.println(password);

}

Selenium Example

public static void login(

        WebDriver driver,

        String username,

        String password) {

 

    driver.findElement(By.id("username"))

            .sendKeys(username);

 

    driver.findElement(By.id("password"))

            .sendKeys(password);

 

    driver.findElement(By.id("login"))

            .click();

}


38. Return Values

A method can return a value to the calling code.

public static int add(int a, int b) {

    return a + b;

}

 

int result = add(10, 20);

 

System.out.println(result);

Selenium Example

public static String getPageTitle(WebDriver driver) {

    return driver.getTitle();

}


39. void Methods

A void method does not return a value.

public static void openPage(WebDriver driver) {

    driver.get("https://example.com");

}


40. Method Overloading

Method overloading allows multiple methods to have the same name with different parameter lists.

public static void search(String product) {

    System.out.println("Product: " + product);

}

 

public static void search(

        String product,

        int quantity) {

 

    System.out.println("Product: " + product);

    System.out.println("Quantity: " + quantity);

}


41. Constructor

A constructor initializes an object when the object is created.

public class LoginPage {

 

    private WebDriver driver;

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

}

Constructors are frequently used in Page Object Model classes to pass the WebDriver instance into a page object.


42. this Keyword

The this keyword refers to the current object.

public class LoginPage {

 

    private WebDriver driver;

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

}


43. Access Modifiers

ModifierMeaning
publicAccessible from other classes
privateAccessible only within the class
protectedAccessible within the package and through inheritance
defaultAccessible within the same package


44. Encapsulation

Encapsulation means keeping data and related operations together while controlling access to internal data.

public class LoginPage {

 

    private WebDriver driver;

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void enterUsername(String username) {

        driver.findElement(By.id("username"))

                .sendKeys(username);

    }

}


45. Inheritance

Inheritance allows a child class to reuse accessible members of a parent class.

public class BasePage {

 

    protected WebDriver driver;

 

    public BasePage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void open(String url) {

        driver.get(url);

    }

}

 

public class LoginPage extends BasePage {

 

    public LoginPage(WebDriver driver) {

        super(driver);

    }

}


46. super Keyword

The super keyword is used to access parent-class members or invoke the parent constructor.

public LoginPage(WebDriver driver) {

    super(driver);

}


47. Method Overriding

Method overriding occurs when a child class provides a specific implementation of a method inherited from a parent class.

class BasePage {

 

    public void open() {

        System.out.println("Opening Base Page");

    }

}

 

class LoginPage extends BasePage {

 

    @Override

    public void open() {

        System.out.println("Opening Login Page");

    }

}


48. Polymorphism

Polymorphism allows a common parent type or interface to refer to different implementations.

WebDriver driver = new ChromeDriver();

Here, WebDriver is the interface reference and ChromeDriver is the concrete implementation.


49. Abstraction

Abstraction hides unnecessary implementation details and exposes the functionality required by the user of a component.

Selenium's WebDriver API is an important example because automation code can work with the WebDriver interface while the actual browser-specific implementation is supplied by classes such as ChromeDriver, FirefoxDriver, EdgeDriver, and SafariDriver. :contentReference[oaicite:2]{index=2}


50. Abstract Class

abstract class BasePage {

 

    abstract void openPage();

 

    public void commonOperation() {

        System.out.println("Common Operation");

    }

}


51. Interface

An interface defines a contract that implementing classes can follow.

interface BrowserActions {

 

    void openBrowser();

 

    void closeBrowser();

}


52. Implementing an Interface

class ChromeActions implements BrowserActions {

 

    public void openBrowser() {

        System.out.println("Opening Chrome");

    }

 

    public void closeBrowser() {

        System.out.println("Closing Chrome");

    }

}


53. WebDriver Interface

WebDriver is one of the most important interfaces in Selenium Java. It provides methods for controlling the browser and finding web elements. Selenium's Java API documentation identifies WebDriver as an interface implemented by browser-specific classes such as ChromeDriver, EdgeDriver, FirefoxDriver, and SafariDriver. :contentReference[oaicite:3]{index=3}

WebDriver driver = new ChromeDriver();


54. Packages

Packages organize related Java classes and help create a clean project structure.

package pages;

Example Automation Structure

selenium-project/

├── src/

│   ├── main/

│   │   └── java/

│   │       ├── pages/

│   │       ├── utils/

│   │       └── base/

│   └── test/

│       └── java/

│           └── tests/

└── pom.xml


55. import Statement

The import statement allows a Java class to use classes from other packages.

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;


56. Selenium Maven Dependency

Maven is commonly used to manage Selenium Java dependencies. Selenium's documentation shows the Selenium Java library being configured through the project's Maven pom.xml. :contentReference[oaicite:4]{index=4}

<dependency>

    <groupId>org.seleniumhq.selenium</groupId>

    <artifactId>selenium-java</artifactId>

    <version>YOUR_SELENIUM_VERSION</version>

</dependency>

Use the Selenium version selected by your project's dependency management rather than hard-coding an outdated version from an old tutorial.


57. Exception Handling

Exception handling allows a Java program to respond to runtime problems without abruptly terminating the entire application.

try {

    int result = 10 / 0;

} catch (ArithmeticException e) {

    System.out.println("Arithmetic error occurred");

}


58. try-catch-finally

try {

    System.out.println("Executing Test");

} catch (Exception e) {

    System.out.println("Error: " + e.getMessage());

} finally {

    System.out.println("Cleanup Completed");

}

Selenium Example

WebDriver driver = new ChromeDriver();

 

try {

    driver.get("https://example.com");

    System.out.println(driver.getTitle());

} finally {

    driver.quit();

}

Using quit() is the standard way to end a WebDriver session; Selenium's documentation specifically distinguishes quit() from close() and recommends quit() for ending the session. :contentReference[oaicite:5]{index=5}


59. Common Selenium Exceptions

ExceptionMeaning
NoSuchElementExceptionElement could not be located
TimeoutExceptionWait condition did not complete within the timeout
ElementNotInteractableExceptionElement cannot currently be interacted with
ElementClickInterceptedExceptionAnother element prevents the click
StaleElementReferenceExceptionPreviously located element is no longer attached to the DOM
InvalidSelectorExceptionLocator syntax is invalid
NoSuchWindowExceptionRequested browser window is unavailable
NoSuchFrameExceptionRequested frame is unavailable


60. throws Keyword

The throws keyword declares that a method may pass an exception to its caller.

public void readFile() throws IOException {

    // File operation

}


61. throw Keyword

The throw keyword is used to explicitly generate an exception.

if (username == null) {

    throw new IllegalArgumentException(

        "Username cannot be null"

    );

}


62. Collections Framework

Java Collections are extremely important in Selenium because automation scripts frequently work with multiple elements, browser windows, test records, and configuration values.

Important collection types include:

  • List
  • ArrayList
  • Set
  • HashSet
  • Map
  • HashMap


63. List

A List stores ordered elements and can contain duplicate values.

List<String> browsers = new ArrayList<>();

 

browsers.add("Chrome");

browsers.add("Firefox");

browsers.add("Edge");

 

System.out.println(browsers);


64. ArrayList

ArrayList<String> users = new ArrayList<>();

 

users.add("admin");

users.add("tester");

 

for (String user : users) {

    System.out.println(user);

}


65. Selenium findElements() with List

Selenium's findElements() method returns multiple matching elements, which can be stored in a Java List.

List<WebElement> links =

        driver.findElements(By.tagName("a"));

 

for (WebElement link : links) {

    System.out.println(link.getText());

}

This is useful for menus, product cards, links, table rows, search results, and other collections of web elements. Selenium's Java first-script documentation demonstrates finding WebElements with the By locator API. :contentReference[oaicite:6]{index=6}


66. Set

A Set stores unique values and does not allow duplicate elements.

Set<String> browsers = new HashSet<>();

 

browsers.add("Chrome");

browsers.add("Firefox");

browsers.add("Chrome");

 

System.out.println(browsers);


67. Window Handles with Set

Selenium browser windows and tabs can be identified using window handles. Java commonly represents the collection of handles with a Set.

String originalWindow = driver.getWindowHandle();

 

Set<String> windows =

        driver.getWindowHandles();

 

for (String window : windows) {

    System.out.println(window);

}


68. Map

A Map stores key-value pairs and is useful for test data.

Map<String, String> user = new HashMap<>();

 

user.put("username", "admin");

user.put("password", "admin123");

 

System.out.println(

    user.get("username")

);

Selenium Example

Map<String, String> loginData =

        new HashMap<>();

 

loginData.put("username", "admin");

loginData.put("password", "admin123");

 

driver.findElement(By.id("username"))

        .sendKeys(loginData.get("username"));

 

driver.findElement(By.id("password"))

        .sendKeys(loginData.get("password"));


69. Generics

Generics provide type safety when working with Java collections.

List<String> names = new ArrayList<>();

 

names.add("John");

names.add("Smith");

Selenium Example

List<WebElement> products =

        driver.findElements(

            By.cssSelector(".product")

        );


70. Wrapper Classes

PrimitiveWrapper Class
intInteger
doubleDouble
booleanBoolean
charCharacter
longLong
floatFloat


71. Autoboxing and Unboxing

int number = 10;

 

Integer boxedNumber = number;

 

int originalNumber = boxedNumber;


72. static Keyword

The static keyword makes a field or method belong to the class rather than to a specific object.

public class TestUtility {

 

    public static void printMessage() {

        System.out.println("Selenium Utility");

    }

}

Calling the static method:

TestUtility.printMessage();


73. final Keyword

The final keyword can prevent reassignment of a variable and can also be applied to methods and classes with different effects.

final String BASE_URL =

        "https://example.com";


74. StringBuilder

StringBuilder can be useful when repeatedly constructing or modifying text.

StringBuilder message =

        new StringBuilder();

 

message.append("Login ");

message.append("Test ");

message.append("Passed");

 

System.out.println(message);


75. Java Date and Time

Date and time APIs can be useful for test data, transaction validation, reports, timestamps, and booking applications.

import java.time.LocalDate;

import java.time.LocalDateTime;

 

LocalDate date = LocalDate.now();

LocalDateTime dateTime = LocalDateTime.now();

 

System.out.println(date);

System.out.println(dateTime);


76. Environment Variables

Environment variables can be used to provide environment-specific or sensitive configuration without putting values directly into source code.

String username =

        System.getenv("TEST_USERNAME");

 

String password =

        System.getenv("TEST_PASSWORD");


77. File Handling

Automation frameworks may need to read configuration files, test data, CSV files, text files, or other resources.

import java.io.FileWriter;

import java.io.IOException;

 

public class FileExample {

 

    public static void main(String[] args)

            throws IOException {

 

        FileWriter writer =

                new FileWriter("result.txt");

 

        writer.write("Login Test Passed");

 

        writer.close();

    }

}


78. Reading a Text File

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

 

BufferedReader reader =

        new BufferedReader(

            new FileReader("data.txt")

        );

 

String line;

 

while ((line = reader.readLine()) != null) {

    System.out.println(line);

}

 

reader.close();


79. Properties File

Properties files are commonly used for framework configuration.

browser=chrome

environment=qa

baseUrl=https://example.com

Reading Properties

Properties properties =

        new Properties();

 

FileInputStream input =

        new FileInputStream(

            "config.properties"

        );

 

properties.load(input);

 

String browser =

        properties.getProperty("browser");


80. Lambda Expressions

Lambda expressions provide a concise way to represent functional behavior.

List<String> browsers =

        Arrays.asList(

            "Chrome",

            "Firefox",

            "Edge"

        );

 

browsers.forEach(browser ->

        System.out.println(browser)

);


81. Java Streams

Streams can be used to process collections in a concise manner.

List<String> browsers =

        Arrays.asList(

            "Chrome",

            "Firefox",

            "Edge"

        );

 

browsers.stream()

        .filter(browser -> browser.length() > 5)

        .forEach(System.out::println);


82. Selenium Java Imports

Common Selenium Java imports include:

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;


83. Creating a WebDriver

WebDriver driver = new ChromeDriver();

Selenium's official Java first-script example follows this basic pattern for creating a Chrome browser session. :contentReference[oaicite:7]{index=7}


84. Opening a URL

driver.get("https://example.com");

The get() method navigates the browser to the specified URL.


85. Getting Page Title

String title = driver.getTitle();

 

System.out.println(title);


86. Getting Current URL

String currentUrl =

        driver.getCurrentUrl();

 

System.out.println(currentUrl);


87. Finding Web Elements

Before interacting with an element, Selenium must locate it using an appropriate locator strategy.

WebElement username =

        driver.findElement(

            By.id("username")

        );

The Selenium Java WebDriver API provides methods such as get() and findElement(By) for browser navigation and element selection. :contentReference[oaicite:8]{index=8}


88. Common Selenium Locators

LocatorJava Syntax
IDBy.id("username")
NameBy.name("username")
Class NameBy.className("login-button")
Tag NameBy.tagName("button")
Link TextBy.linkText("Login")
Partial Link TextBy.partialLinkText("Log")
CSS SelectorBy.cssSelector("#username")
XPathBy.xpath("//input[@id='username']")


89. WebElement Methods

WebElement username =

        driver.findElement(

            By.id("username")

        );

 

username.clear();

 

username.sendKeys("admin");

 

WebElement login =

        driver.findElement(

            By.id("login")

        );

 

login.click();

Important WebElement Methods

  • click()
  • sendKeys()
  • clear()
  • getText()
  • getAttribute()
  • isDisplayed()
  • isEnabled()
  • isSelected()


90. Basic Selenium Login Script

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class LoginTest {

 

    public static void main(String[] args) {

 

        WebDriver driver =

                new ChromeDriver();

 

        try {

            driver.get(

                "https://example.com/login"

            );

 

            driver.findElement(

                By.id("username")

            ).sendKeys("admin");

 

            driver.findElement(

                By.id("password")

            ).sendKeys("admin123");

 

            driver.findElement(

                By.id("login")

            ).click();

 

        } finally {

            driver.quit();

        }

    }

}


91. Selenium Navigation Methods

driver.get("https://example.com");

 

driver.navigate().to(

    "https://example.com"

);

 

driver.navigate().back();

 

driver.navigate().forward();

 

driver.navigate().refresh();


92. Browser Window Management

driver.manage()

      .window()

      .maximize();

 

driver.manage()

      .window()

      .minimize();

 

driver.manage()

      .window()

      .fullscreen();


93. Selenium Wait Basics

Modern web applications often load content dynamically. Java Selenium provides waiting mechanisms that can synchronize automation with application behavior.

Implicit Wait

driver.manage()

      .timeouts()

      .implicitlyWait(

          Duration.ofSeconds(10)

      );

Selenium's official Java example demonstrates configuring an implicit wait through the WebDriver timeout API. :contentReference[oaicite:9]{index=9}

Explicit Wait

WebDriverWait wait =

        new WebDriverWait(

            driver,

            Duration.ofSeconds(10)

        );

 

WebElement element =

        wait.until(

            ExpectedConditions

                .visibilityOfElementLocated(

                    By.id("username")

                )

        );


94. Selenium Assertions

Assertions compare the actual result of an application with the expected result.

String expectedTitle = "Dashboard";

String actualTitle = driver.getTitle();

 

if (expectedTitle.equals(actualTitle)) {

    System.out.println("Test Passed");

} else {

    System.out.println("Test Failed");

}

In structured Selenium projects, testing frameworks such as JUnit and TestNG can provide dedicated assertion and test-execution functionality. Selenium's documentation lists both JUnit and TestNG among commonly used test runners. :contentReference[oaicite:10]{index=10}


95. Java with TestNG

TestNG can organize Java Selenium tests into test methods and suites.

import org.testng.annotations.Test;

 

public class LoginTest {

 

    @Test

    public void loginTest() {

        System.out.println("Login Test");

    }

}


96. Java with JUnit

JUnit is another popular testing framework for Java automation.

import org.junit.jupiter.api.Test;

 

public class LoginTest {

 

    @Test

    void loginTest() {

        System.out.println("Login Test");

    }

}


97. Page Object Model

Page Object Model, or POM, is a design approach in which page-specific locators and actions are organized into dedicated classes. It helps reduce duplication and improves maintainability.

public class LoginPage {

 

    private WebDriver driver;

 

    private By username =

            By.id("username");

 

    private By password =

            By.id("password");

 

    private By loginButton =

            By.id("login");

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void login(

            String user,

            String pass) {

 

        driver.findElement(username)

                .sendKeys(user);

 

        driver.findElement(password)

                .sendKeys(pass);

 

        driver.findElement(loginButton)

                .click();

    }

}


98. Base Page

A BasePage can contain common functionality shared by several page objects.

public class BasePage {

 

    protected WebDriver driver;

 

    public BasePage(WebDriver driver) {

        this.driver = driver;

    }

 

    public String getTitle() {

        return driver.getTitle();

    }

 

    public void open(String url) {

        driver.get(url);

    }

}


99. Utility Class

Utility classes contain reusable functionality such as browser operations, waits, screenshots, data processing, and configuration handling.

public class BrowserUtils {

 

    public static void openUrl(

            WebDriver driver,

            String url) {

 

        driver.get(url);

    }

 

    public static String getTitle(

            WebDriver driver) {

 

        return driver.getTitle();

    }

}


100. Complete Selenium Project Structure

selenium-java-project/

│

├── pom.xml

│

├── src/

│   ├── main/

│   │   └── java/

│   │       ├── base/

│   │       ├── pages/

│   │       └── utils/

│   │

│   └── test/

│       └── java/

│           └── tests/

│

├── src/test/resources/

│   ├── config.properties

│   └── testdata/

│

└── README.md


101. Practical Project: Login Automation

Objective

Create a Java Selenium program that opens a login page, enters credentials, clicks the login button, and validates the result.

Automation Flow

Start Program

      ↓

Create WebDriver

      ↓

Open Login URL

      ↓

Locate Username

      ↓

Enter Username

      ↓

Locate Password

      ↓

Enter Password

      ↓

Click Login

      ↓

Validate Result

      ↓

Quit Browser


102. Practical Project: Product Search

Create a Selenium Java script that opens an e-commerce application, searches for a product, retrieves matching product elements, and prints their names.

Concepts Used

  • Variables
  • Strings
  • Methods
  • Lists
  • Loops
  • WebDriver
  • WebElement
  • Locators


103. Practical Project: Multiple User Test Data

Use Java collections to store multiple user records and pass them to a reusable login method.

List<Map<String, String>> users =

        new ArrayList<>();

 

Map<String, String> user1 =

        new HashMap<>();

 

user1.put("username", "admin");

user1.put("password", "admin123");

 

users.add(user1);

 

for (Map<String, String> user : users) {

    System.out.println(

        user.get("username")

    );

}


104. Practical Project: Page Object Model

Create separate classes such as LoginPage, HomePage, ProductPage, CartPage, and CheckoutPage. Keep page-specific locators and actions inside the appropriate classes.

Test Class

    ↓

LoginPage

    ↓

HomePage

    ↓

ProductPage

    ↓

CartPage

    ↓

CheckoutPage


105. Common Java Mistakes in Selenium

  • Using == instead of equals() for String content comparison.
  • Creating extremely large methods.
  • Using unclear variable names.
  • Duplicating Selenium code across many test classes.
  • Hard-coding credentials into source code.
  • Ignoring exceptions without understanding their cause.
  • Not closing WebDriver sessions.
  • Using unnecessary fixed delays.
  • Keeping all locators directly inside test methods.
  • Mixing test data and test logic unnecessarily.
  • Using inheritance where composition would be simpler.
  • Creating overly complicated utility classes.


106. Best Practices for Java Selenium

  1. Use meaningful class and method names.
  2. Follow Java naming conventions.
  3. Keep methods small and focused.
  4. Create reusable methods for repeated operations.
  5. Use Page Object Model for larger projects.
  6. Keep locators organized.
  7. Use explicit waits for dynamic conditions.
  8. Avoid unnecessary hard-coded delays.
  9. Use driver.quit() to properly end browser sessions.
  10. Keep credentials outside source code.
  11. Use Maven or Gradle for dependency management.
  12. Use TestNG or JUnit for structured test execution.
  13. Use logging and reporting in larger frameworks.
  14. Separate test data from test implementation.
  15. Use version control such as Git.


107. Java Concepts Required for Advanced Selenium

Java ConceptUse in Selenium
VariablesStore URLs, credentials, values and objects
Data TypesRepresent test data
ConditionsImplement decision logic
LoopsProcess multiple elements
ArraysStore multiple values
MethodsCreate reusable actions
ClassesOrganize framework components
ObjectsCreate instances of classes
InheritanceReuse framework behavior
PolymorphismWork with interfaces and implementations
AbstractionHide implementation details
CollectionsHandle multiple elements and test data
Exception HandlingHandle runtime problems
File HandlingRead configuration and test data
PackagesOrganize automation source code
MavenManage dependencies and builds


108. Java vs Selenium Responsibilities

JavaSelenium
VariablesBrowser control
ConditionsElement interaction
LoopsProcessing multiple elements
MethodsBrowser operations
ClassesPage Objects
CollectionsWebElement and window collections
Exception HandlingBrowser and element operations
OOPAutomation framework architecture


109. Java Selenium Learning Flow

Java Syntax

      ↓

Variables & Data Types

      ↓

Operators

      ↓

Conditions

      ↓

Loops

      ↓

Arrays & Strings

      ↓

Methods

      ↓

Classes & Objects

      ↓

Constructors

      ↓

OOP Concepts

      ↓

Collections

      ↓

Exception Handling

      ↓

Packages

      ↓

File Handling

      ↓

Maven

      ↓

Selenium WebDriver

      ↓

Locators

      ↓

WebElements

      ↓

Waits

      ↓

Page Object Model

      ↓

TestNG / JUnit

      ↓

Automation Framework


110. Interview Questions

Q1. What is Java?

Java is a high-level, object-oriented programming language widely used for application development and automation.

Q2. Why is Java used with Selenium?

Java provides the programming language and OOP capabilities needed to implement Selenium automation scripts and scalable frameworks.

Q3. What is JDK?

JDK stands for Java Development Kit and provides tools required to develop and compile Java applications.

Q4. What is a class?

A class is a blueprint for creating objects.

Q5. What is an object?

An object is an instance of a class.

Q6. What is inheritance?

Inheritance allows a child class to reuse accessible members of a parent class.

Q7. What is polymorphism?

Polymorphism allows a common parent type or interface to represent different implementations.

Q8. What is encapsulation?

Encapsulation combines data and behavior while controlling access to internal implementation details.

Q9. What is the difference between == and equals()?

For objects such as Strings, == compares references, while equals() is used to compare content when the class implements it appropriately.

Q10. What is an ArrayList?

ArrayList is a resizable implementation of the List interface.

Q11. Why are collections important in Selenium?

Collections are useful for handling multiple WebElements, window handles, test records, and configuration values.

Q12. What is an interface?

An interface defines a contract that implementing classes can follow.

Q13. What is a constructor?

A constructor initializes an object when it is created.

Q14. What is exception handling?

Exception handling provides mechanisms such as try, catch, finally, throw, and throws for handling runtime problems.

Q15. What is Page Object Model?

Page Object Model organizes page-specific locators and actions into dedicated classes to improve maintainability and reuse.

Q16. What is Maven?

Maven is a Java build and dependency-management tool commonly used to manage Selenium project dependencies.

Q17. What is WebDriver?

WebDriver is a Selenium interface used to control browsers and interact with web applications.

Q18. What is WebElement?

WebElement represents an element in a web page's DOM and provides methods for actions and information retrieval.


111. Quick Revision Table

TopicKey Point
JavaProgramming language used to implement Selenium logic
JDKJava development environment
VariableStores a value
StringStores text
BooleanStores true or false
ArrayStores multiple values
MethodReusable block of code
ClassBlueprint for objects
ObjectInstance of a class
ConstructorInitializes objects
InheritanceReuses behavior from a parent class
PolymorphismSupports different implementations through common types
InterfaceDefines a contract
ListOrdered collection
SetUnique-value collection
MapKey-value collection
ExceptionRuntime problem that can be handled
WebDriverSelenium browser-control interface
WebElementRepresents a web element
ByProvides locator strategies
MavenBuild and dependency management tool


112. Recommended Learning Sequence

  1. Learn Java syntax.
  2. Understand variables and data types.
  3. Practice operators.
  4. Learn conditional statements.
  5. Practice loops.
  6. Learn arrays and Strings.
  7. Learn methods and parameters.
  8. Understand classes and objects.
  9. Learn constructors and this.
  10. Understand inheritance and polymorphism.
  11. Learn abstraction and interfaces.
  12. Practice Java collections.
  13. Learn exception handling.
  14. Learn packages and imports.
  15. Practice file handling.
  16. Learn Maven basics.
  17. Install Selenium Java.
  18. Learn WebDriver.
  19. Learn locators and WebElements.
  20. Learn waits and synchronization.
  21. Learn Page Object Model.
  22. Learn TestNG or JUnit.
  23. Build a complete Selenium automation framework.


113. Final Summary

Java Basics for Selenium provides the programming foundation required to build Selenium WebDriver automation scripts and scalable testing frameworks. A Selenium learner should be comfortable with variables, data types, operators, conditions, loops, arrays, Strings, methods, classes, objects, constructors, inheritance, polymorphism, abstraction, interfaces, collections, exception handling, packages, file handling, and Maven.

After learning these concepts, learners can work with Selenium classes and interfaces such as WebDriver, WebElement, By, and browser-specific drivers. A basic Selenium Java workflow consists of starting a browser session, navigating to a page, finding elements, interacting with them, retrieving information, validating results, and ending the session. :contentReference[oaicite:11]{index=11}

The next stage is to learn Selenium locators, WebElement methods, waits, alerts, frames, windows, dropdowns, Actions API, screenshots, JavaScript execution, Page Object Model, TestNG or JUnit, data-driven testing, reporting, Maven, Selenium Grid, and CI/CD integration.


Course Resources

JustAcademy Selenium Training: https://www.justacademy.co/course-detail/selenium-training

Register for Course Demo: https://www.justacademy.co/register-for-course-demo

whatsapp